package com.example.run_game;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.concurrent.ArrayBlockingQueue;

import org.apache.http.HttpStatus;
import org.xml.sax.SAXException;

import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.SoundPool;
import android.media.SoundPool.OnLoadCompleteListener;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;

///Very rough, does nothing yet. But this is the outline
// http://www.vogella.com/articles/AndroidMedia/article.html
public class SoundManager
{	
	private SoundPool soundPool;
	private Context cont;
	private Hashtable<String, Integer> soundLibrary;
	private Hashtable<String, Integer> soundDuration;
	private AssetManager am;
	ArrayBlockingQueue<String> queue;
	
	private Handler sound_handler;
	private Handler duration_handler;
	
	SoundManager(Context contIn, AssetManager amIn)
	{
		cont = contIn;
		am = amIn;
		soundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
		soundLibrary = new Hashtable<String, Integer>();
		queue = new ArrayBlockingQueue<String>(100);
		new ASyncDurationManager().execute();
		soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() 
		{
		  @Override
		  public void onLoadComplete(SoundPool soundPool, int soundID, int status)
		  {			  
			  float volume = getVol();	
			  soundLibrary.put("filename", soundID);
			  soundPool.play(soundID, volume, volume, 1, 0, 1f);
			  //Log.d("Sound", "Played After Loading");
		  }
		});		
	}
	
	private class ASyncDurationManager extends AsyncTask<Void, Void, Hashtable<String,Integer>>
	{
		@Override
		protected Hashtable doInBackground(Void... arg0)
		{   	
			Hashtable<String, Integer> sounds = new Hashtable<String, Integer>();
			MediaPlayer mp = new MediaPlayer();
			AssetFileDescriptor afd;
			AssetManager aMan = cont.getAssets();
			try
			{
				String[] filelist = aMan.list("sounds");
				for (int i=0;i<filelist.length;i++)
				{
					if (filelist[i].contains(".mp3"))
					{
						afd = cont.getAssets().openFd("sounds/"+filelist[i]);
						mp.reset();
						mp.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
						mp.prepare();
						int duration = mp.getDuration();
						System.out.println("FILE LIST::::::::::::::"+filelist[i]+" "+duration);
						sounds.put(filelist[i], duration);
					}
				}

			} catch (IOException e)
			{
				e.printStackTrace();
			}			 
			return sounds;		    	 
	     }

		
		protected void onPostExecute(Hashtable<String, Integer> result)
		{
			soundDuration = result;
		}
   	     
	}
	
	private class ASyncPlaySound extends AsyncTask<String[], Void, String>
	{
		@Override
		protected String doInBackground(String[]... arg0)
		{
			if (soundDuration == null)
				return "";
			String[][] files = arg0;
			float volume = getVol();
			for (int i=0;i<files[0].length;i++)
			{
				String filename = files[0][i];
				if (filename!=null && filename!="")
				{
					int duration = soundDuration.get(filename);
					System.out.println("FILENAME TO LOAD: "+filename + " "+duration);

					/*try
					{
						System.out.println("QUEUEUEUEUEUEUEUEUEUEUEUEUEUEUEUEUE: "+queue.take());
					} catch (InterruptedException e1)
					{
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}*/
					if(soundLibrary.containsKey(filename))		
					{		
						soundPool.play((Integer)soundLibrary.get(filename), volume, volume, 1, 0, 1f);
						//Log.d("Sound", "Played from the HashTable");
					}
					else
					{
						try
						{
							soundPool.load(am.openFd("sounds/"+filename), 1);
						} 
						catch (IOException e)
						{
							e.printStackTrace();
						}
					}
					try
					{
						Thread.sleep(duration);
					} catch (InterruptedException e)
					{
						e.printStackTrace();
					}
				}
			}
			
			return "Sound Played";		
		}
		
		protected void onPostExecute(String result)
		{
			System.out.println(result);
		}
   	     
	 }
			
	void playSound(String[] filenames)
	{
		//queue.add(filenames[0]);
		//queue.add(filenames[1]);
		new ASyncPlaySound().execute(filenames);
	}
		
	private float getVol()
	{
	    AudioManager audioManager = (AudioManager) cont.getSystemService(Context.AUDIO_SERVICE);
	    float actualVolume = (float) audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
	    float maxVolume = (float) audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
	    float volume = actualVolume / maxVolume;
	    return volume;
	}
}
